package org.fmi.lje.graphics.model.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.fmi.lje.graphics.layout.HierarchyLayoutManager;
import org.fmi.lje.graphics.model.Clazz;
import org.fmi.lje.graphics.model.Relationship;

public class BcelHierarchyLayoutManager extends HierarchyLayoutManager {

	@Override
	public void addAll(Collection<? extends Clazz> allClasses) {
		List<BcelClazz> aClasses = new ArrayList<BcelClazz>();
		
		for(Clazz clazz : allClasses) {
			assert clazz instanceof BcelClazz;
			
			aClasses.add((BcelClazz) clazz);
		}

		makeHierarchy(aClasses);
	}

	private void makeHierarchy(List<BcelClazz> allClasses) {
		Set<BcelClazz> roots = new HashSet<BcelClazz>();
		
		for(BcelClazz clazz : allClasses) {
			if(clazz.getSuperclasses().size() == 0) {
				roots.add(clazz);
			}
		}
		
		for(BcelClazz clazz : roots) {
			bfAdd(clazz, 0);
		}
	}
	
	private void bfAdd(BcelClazz root, int row) {
		add(root, row);
		
		for(Relationship r : root.getSubclasses()) {
			bfAdd((BcelClazz)r.getTo(), row + 1);
		}
	}
}
